from django import forms
from django.core.exceptions import ValidationError

from .models import (
    Department,
    Association,
    DepartmentPost,
    AssociationPost,
)
from .validations import (
    valid_created_time,
    valid_contact,
    valid_logo_image,
)


# 在此添加各种表单类
class AssociationForm(forms.ModelForm):
    class Meta:
        model = Association
        exclude = ['owner', 'status', ]
        localized_fields = ('created_time',)
        widgets = {
            'desc': forms.Textarea(),
            'image': forms.ClearableFileInput(
                attrs={
                    'id': 'file',
                    'type': 'file',
                    'class': 'hidden',
                    'accept': 'image/jpeg,image/tiff,image/png,image/bmp,image/gif,image/jpg',
                }
            ),
            'created_time': forms.DateInput(
                attrs={
                    'type': 'date',
                    'style': 'line-height: unset',
                }
            ),
        }
        # 个性化标签，非必要
        labels = {
            'name': "社团名称",
            'desc': "社团简介",
            'content': "详细介绍",
            'image': "社团logo",
            'campus': "所属校区",
            'created_time': "成立时间",
            'number': "社团人数",
            'contact': "联系电话",
            'email': "电子邮箱",
            'principal': "社团负责人",
        }
        # 个性化验证错误信息，非必要
        error_messages = {
            'name': {
                'required': "社团名称不能为空",
                'max_length': "社团名称最长不能超过40个字符",
            },
            'desc': {
                'required': "社团简介不能为空",
                'max_length': "简介最长不能超过500个字符",
            },
            'content': {
                'required': "详细介绍不能为空",
            },
            'image': {
                'required': "请上传社团logo图片",
            },
            'campus': {
                'required': "请选择社团所属校区",
            },
            'created_time': {
                'required': "社团成立时间不能为空",
            },
            'contact': {
                'max_length': "联系电话最长不能超过20个字符",
            },
            'email': {
                'invalid': "电子邮箱填写格式有误",
            },
            'principal': {
                'max_length': "社团负责人信息最长不能超过20个字符",
            },
        }

    def __init__(self, *args, **kwargs):
        super(AssociationForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'

    def clean_image(self):
        """局部钩子，自定义验证规另外验证字段内容"""
        image = self.cleaned_data.get('image')
        error_message = valid_logo_image(image)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return image

    def clean_created_time(self):
        created_time = self.cleaned_data.get('created_time')
        error_message = valid_created_time(created_time)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return created_time

    def clean_contact(self):
        contact = self.cleaned_data.get('contact')
        error_message = valid_contact(contact)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return contact


class DepartmentForm(forms.ModelForm):
    class Meta:
        model = Department
        exclude = ['owner', 'status', ]
        localized_fields = ('created_time',)
        widgets = {
            'desc': forms.Textarea(),
            'image': forms.ClearableFileInput(
                attrs={
                    'id': 'file',
                    'type': 'file',
                    'class': 'hidden',
                    'accept': 'image/jpeg,image/tiff,image/png,image/bmp,image/gif,image/jpg',
                }
            ),
            'created_time': forms.DateInput(
                attrs={
                    'type': 'date',
                    'style': 'line-height: unset',
                }
            ),
        }
        labels = {
            'name': "部门名称",
            'desc': "部门简介",
            'content': "详细介绍",
            'image': "部门logo",
            'college': "所属院系",
            'created_time': "成立时间",
            'number': "部门人数",
            'contact': "联系电话",
            'email': "电子邮箱",
            'principal': "部门负责人",
        }
        error_messages = {
            'name': {
                'required': "部门名称不能为空",
                'max_length': "部门名称最长不能超过40个字符",
            },
            'desc': {
                'required': "部门简介不能为空",
                'max_length': "简介最长不能超过500个字符",
            },
            'content': {
                'required': "详细介绍不能为空",
            },
            'image': {
                'required': "请上传部门logo图片",
            },
            'college': {
                'required': "请选择部门所属院系",
            },
            'created_time': {
                'required': "部门成立时间不能为空",
            },
            'contact': {
                'max_length': "联系电话最长不能超过20个字符",
            },
            'email': {
                'invalid': "电子邮箱填写格式有误",
            },
            'principal': {
                'max_length': "部门负责人信息最长不能超过20个字符",
            },
        }

    def __init__(self, *args, **kwargs):
        super(DepartmentForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'

    def clean_image(self):
        image = self.cleaned_data.get('image')
        error_message = valid_logo_image(image)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return image

    def clean_created_time(self):
        created_time = self.cleaned_data.get('created_time')
        error_message = valid_created_time(created_time)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return created_time

    def clean_contact(self):
        contact = self.cleaned_data.get('contact')
        error_message = valid_contact(contact)
        if error_message:
            raise ValidationError(message=error_message, code='invalid')
        else:
            return contact


class AssociationPostForm(forms.ModelForm):
    class Meta:
        model = AssociationPost
        # 表单字段排除名单
        exclude = ['author', 'created_time', 'modified_time', 'nov', 'nol', ]
        widgets = {
            'desc': forms.Textarea(),
        }
        # 提示信息
        labels = {
            'association': "所属社团",
            'title': "标题",
            'desc': "摘要",
            'content': "正文",
            'status': "状态",
        }
        # 校验不通过的自定义错误提示
        error_messages = {
            'association': {
                'required': "所属社团不能为空",
            },
            'title': {
                'required': "标题不能为空",
                'max_length': "标题最长不能超过40个字符",
            },
            'desc': {
                'max_length': "文章摘要最长不能超过200个字符",
            }
        }

    # 批量添加共同属性：向django Form窗体中添加form-control窗体控件，可以不使用django自带的窗体控件自定义船体空间
    def __init__(self, *args, **kwargs):
        super(AssociationPostForm, self).__init__(*args, **kwargs)
        # 过滤掉待审核的社团，仅展示公开社团
        self.fields['association'].queryset = Association.get_all_normal_associations()
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'


class DepartmentPostForm(forms.ModelForm):
    class Meta:
        model = DepartmentPost
        exclude = ['author', 'created_time', 'modified_time', 'nov', 'nol', ]
        widgets = {
            'desc': forms.Textarea(),
        }
        labels = {
            'department': "所属部门",
            'title': "标题",
            'desc': "摘要",
            'content': "正文",
            'status': "状态",
        }
        error_messages = {
            'department': {
                'required': "所属部门不能为空",
            },
            'title': {
                'required': "标题不能为空",
                'max_length': "标题最长不能超过40个字符",
            },
            'desc': {
                'max_length': "文章摘要最长不能超过200个字符",
            }
        }

    def __init__(self, *args, **kwargs):
        super(DepartmentPostForm, self).__init__(*args, **kwargs)
        self.fields['department'].queryset = Department.get_all_normal_departments()
        for field_name, field in self.fields.items():
            if field.widget.attrs.get('class'):
                field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs['class'] = 'form-control'
